package api;

import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.mysql.jdbc.Connection;
import lombok.SneakyThrows;
import model.Article;
import model.UserInfo;
import util.AppVar;
import util.DBUtils;
import util.ResultUtils;
import util.SessionUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

/**
 * 获取我的文章详情
 */
@WebServlet("/myarticlelist")
public class MyArticleListServlet extends HttpServlet {
    @SneakyThrows
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String msg="未知错误";
        List<Article> list=new ArrayList<>();
        UserInfo userInfo= SessionUtils.getLoginUser(req);
        //1.得到前端的参数
        if(userInfo!=null){
            int uid=userInfo.getUid();
            if(uid>0){
                //2.查询数据库，并返回数据
                Connection connection = DBUtils.getConnection();
                String sql="select * from article where uid=? order by aid desc";
                PreparedStatement statement = connection.prepareStatement(sql);
                statement.setInt(1,uid);
                ResultSet resultSet = statement.executeQuery();
                //将查询的结果添加到容器中
                while (resultSet.next()){
                    String context=resultSet.getString("context");//文章正文
                    Article article=new Article();
                    article.setAid(resultSet.getInt("aid"));
                    article.setTitle(resultSet.getString("title"));
                    article.setContext(context);
                    //简介
                    int subLength=Integer.min(20,context.length());
                    article.setDesc(context.substring(0,subLength).replace("#",""));
                    String createTime=resultSet.getString("createtime");
                    article.setCreatetime(createTime.substring(0,createTime.lastIndexOf(".")));
                    article.setReadcount(resultSet.getInt("readcount"));
                    article.setUid(resultSet.getInt("uid"));
                    article.setState(resultSet.getInt("state"));
                    list.add(article);
                }
                //关闭资源
                DBUtils.close(resultSet,statement,connection);
            }else {
                msg="非法参数";
            }
        }else{
            msg="请先登录";
        }
        //3.将数据返回给前端
        resp.setContentType(AppVar.RESPONSE_CONTENTTYPE_JSON);
        resp.getWriter().println(JSONUtil.toJsonStr(ResultUtils.toResult(200,list,msg)));
    }
}
